var common = require('../../../utils/common.js');
var app = getApp();
var baseUrl = app.url;
var sliderWidth = 96; 

Page({
    data: {
        tabs: ["通用信息", "智能设备", "电子文件"],
        activeIndex: 0,
        sliderOffset: 0,
        sliderLeft: 0,
        b_index:0,
        car_breed:['小型轿车','SUV','客车'],
        breed_key:0,
        multiArray:[],
        multiIndex: [0,0],
        relevance:["请选择","分时租赁","企业用车","共享用车","长租车辆","自测试用","上牌整备","整备待租"],
        relev_id:0,
        agency_id:0,
        supplier:[{id:"",name:"请选择"},{id:1376920002,name:"博鹭途"},{id:1376920001,name:"唯特迅"},{id:1376920003,name:"博鹭途(IOT)"}],
        supp_id:0,
        b_supp_id:0,
        files:[[],[],[]],
        __UPLOADS__:app.__UPLOADS__,
        __PUBLIC__:app.__PUBLIC__,
        filesNum:0,


    },
    onShow: function () {
        var id = this.data.id;
        var that = this;
        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
                    sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
                });
            }
        });
        common.bestCurl('GET','/cars/edit',res=>{
            if(res.statusCode == 200){
                if(res.data.length!=0){ 
                    var agency_name = this.data.agency_name;
                    for(var index in res.data.agency){
                        if(res.data.agency[index]['name']==agency_name){
                            this.setData({agency_id:index});
                        }
                    }
                    var brand_name = this.data.brand_name;
                    for(var key in res.data.brand){
                        if(res.data.brand[key]['name']==brand_name){
                            this.setData({b_index:key})
                        }
                    }
                    multiArray = [[{id:0,name:'公司'}],[{id:1,name:'个人'}]];
                    multiArray[1] = res.data.holder;
                    var holder_name = this.data.holder_name;
                    for(var val in res.data.holder){
                        if(res.data.holder[val]['name']==holder_name){
                            // console.log(val)
                           // this.setData({multiArray[1][multiIndex[1]]:val})
                        }
                    }
                    this.setData({brand_id:res.data.brand,multiArray:multiArray,agency:res.data.agency})
                }
            }
        },{'id':id}) 

    },
    onLoad:function(options){
        var id = options.id;
        this.setData({id:id})
        common.bestCurl('GET','/cars/details',res=>{      
            if(res.statusCode==200){
                if(res.data.code!=0){
                    var supplier_no = res.data.supplier_no;
                    var supplier = this.data.supplier;
                    for(var index in supplier){
                        if(supplier[index]['id']==supplier_no){
                            this.setData({supp_id:index})
                        }
                    }
                    console.log(res.data);
                    if(res.data.car_file.length!=0){
                        var file_arr = [[],[],[]];
                        var dataArr = [];
                        var j = 0;
                        var k = 0;
                        var l = 0;
                        for(var i=0;i<res.data.car_file.length;i++){
                            if(res.data.car_file[i].file_type == 0){
                                url = app.__UPLOADS__+'/'+res.data.car_file[i].file_url;
                                let id = res.data.car_file[i].id;
                                file_arr[0][j] = {'kind':1,'url':url,'show_url':url,'id':id};
                                j++;
                            }else if(res.data.car_file[i].file_type == 1){
                                url = app.__UPLOADS__+'/'+res.data.car_file[i].file_url;
                                let id = res.data.car_file[i].id;
                                file_arr[1][k] = {'kind':1,'url':url,'show_url':url,'id':id};
                                k++;
                            }else if(res.data.car_file[i].file_type == 2){
                                url = app.__UPLOADS__+'/'+res.data.car_file[i].file_url;
                                let id = res.data.car_file[i].id;
                                file_arr[2][l] = {'kind':1,'url':url,'show_url':url,'id':id};
                                l++;
                            }
                        }  
                        this.setData({details:res.data,files:file_arr,relev_id:res.data.relevance,agency_name:res.data.agency_name,brand_name:res.data.brand_name,holder_name:res.data.holder_name,breed_key:res.data.car_breed}) 
                    }else{
                        this.setData({details:res.data,relev_id:res.data.relevance,agency_name:res.data.agency_name,brand_name:res.data.brand_name,holder_name:res.data.holder_name,breed_key:res.data.car_breed})
                    }    
                }
            }
        },{'id':id})
    },
    tabClick: function (e) {
        this.setData({
            sliderOffset: e.currentTarget.offsetLeft,
            activeIndex: e.currentTarget.id
        });
    },
    bindMultiPickerColumnChange:function(e){
        console.log(e.detail.value)
        this.setData({
          multiColumnIndex: e.detail.value
        })
    },
    bindBrandChange: function (e) {
        this.setData({
            b_index: e.detail.value
        })
    },   
    bindBreedChange: function (e) {
        this.setData({
            breed_key: e.detail.value
        })
    },
    bindMultiPickerChange: function (e) {
        console.log(e.detail.value)
        this.setData({
          multiIndex: e.detail.value
        })
    }, 
    bindRelevChange:function (e) {
        this.setData({
            relev_id: e.detail.value
        })
    },
    agencyChange:function (e) {
       this.setData({
            agency_id: e.detail.value
        })
    }, 
    bindSuppChange:function (e) {
        this.setData({
            supp_id: e.detail.value
        })
    }, 
    bindBsuppChange:function (e) {
        this.setData({
            b_supp_id: e.detail.value
        })
    },
    chooseImage: function (e) {
        kind = e.currentTarget.dataset.kind;
        var file_type = e.target.id;
        var that = this;
        var files = this.data.files;
        wx.chooseImage({
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: function (res) {
                if(file_type == 0){
                    var arr = [];
                    for(var i=0;i<res.tempFilePaths.length;i++){
                        arr[i] = new Object;
                        arr[i]['id'] = 0;
                        arr[i]['kind'] =2;
                        arr[i]['url'] = res.tempFilePaths[i];
                        arr[i]['show_url'] = res.tempFilePaths[i];
                    }
                    var file = that.data.files[0];
                    var fileUrl = file.concat(arr);
                    files.splice(0,1,fileUrl)
                }else if(file_type == 1){
                    var arr = [];
                    for(var i=0;i<res.tempFilePaths.length;i++){
                        arr[i] = new Object;
                        arr[i]['id'] = 0;
                        arr[i]['kind'] =2;
                        arr[i]['url'] = res.tempFilePaths[i];
                        arr[i]['show_url'] = res.tempFilePaths[i];
                    }
                    var file = that.data.files[1];
                    var fileUrl = file.concat(arr);
                    files.splice(1,1,fileUrl)
                }else if(file_type == 2){
                    var arr = [];
                    for(var i=0;i<res.tempFilePaths.length;i++){
                        arr[i] = new Object;
                        arr[i]['id'] = 0;
                        arr[i]['kind'] =2;
                        arr[i]['url'] = res.tempFilePaths[i];
                        arr[i]['show_url'] = res.tempFilePaths[i];
                    }
                    var file = that.data.files[2];
                    var fileUrl = file.concat(arr);
                    files.splice(2,1,fileUrl)
                }
                that.setData({files:files,filesNum:that.data.filesNum+res.tempFilePaths.length})
            }
        })
    },
    previewImage: function(e){
        var url = e.currentTarget.dataset.url;
        var fileUrl = url;
        var extStart = url.lastIndexOf(".");
        var ext = url.substring(extStart, url.length).toUpperCase();
        var pic = [
            '.JPG',
            '.PNG',
            '.JPEG',
            '.BMP',
            '.GIF',
            '.WEBP'
        ];
        var fileType = [
            '.DOC',
            '.XLS',
            '.PPT',
            '.PDF',
            '.DOCX',
            '.XLSX',
            '.PPTX'
        ];
        if(pic.indexOf(ext)!=-1){
            wx.previewImage({
                current: '', 
                urls: [
                    fileUrl
                ] 
            })
        }else if(fileType.indexOf(ext)!=-1){
            wx.showLoading({
              title: '加载中',
              mask:true
            });
            wx.downloadFile({
                url: fileUrl, 
                success: function(res) {
                    wx.hideLoading();
                    if (res.statusCode === 200) {
                        wx.openDocument({
                            filePath: res.tempFilePath,
                            success: function (res) {
                                console.log('打开文档成功')
                            }
                        })
                    }
                }
            });
        }else{
            wx.showModal({
                content: '非法文件,禁止预览',
                showCancel: false,
            });        
        }   
    },
    clickWrongIcon:function(event){
        id = event.target.id;
        var obj = this.data.files;
        var that = this; 
        var type = event.currentTarget.dataset.type;
        if(event.currentTarget.dataset.files.kind == 1){
            wx.showModal({
                title: '确认要删除吗?',
                cancelText: "取消",
                confirmText: "确定",
                success: function (res) {
                    if (res.confirm) {
                        common.bestCurl('GET','/cars/del_file',res=>{
                            if(res.statusCode == 200){
                                if(res.data.code == 1){
                                    wx.showToast({
                                        title: '删除成功',
                                        icon: '',
                                        duration: 2000
                                    });
                                    setTimeout(function(){
                                        obj[type].splice(id,1); 
                                        that.setData({files:obj});
                                    },2000)
                                }else{
                                    wx.showToast({
                                        title: '未删除成功,请重试',
                                        icon: '',
                                        duration: 3000
                                    });
                                }
                            }
                        },{'id':event.currentTarget.dataset.files.id})
                    }else{
                        console.log('用户点击辅助操作')
                    }
                }
            });
        }else{
            let files = this.data.files;
            let filesNum = this.data.filesNum;
            files[type].splice(id,1);
            if(filesNum>0){
                filesNum--;
            }
            this.setData({files:files,filesNum:filesNum})
        } 
    },
    notPic:function (event) {
        index = event.currentTarget.dataset.index;
        type = event.currentTarget.dataset.type;
        var files = this.data.files;
        var filesArr = this.data.files[type][index];
        
        filesArr['show_url'] = app.__PUBLIC__+'/images/PDF.png';
        files[type].splice(index,1,filesArr);
        this.setData({files:files})
    },
    formSubmit:function (event) {
        var id = event.currentTarget.id;
        var formData = event.detail.value;
        let appData = this.data;
        let data = [];
        data['holder_type'] = appData.multiArray[0][appData.multiIndex[0]].id
        data['holder_id'] = appData.multiArray[1][appData.multiIndex[1]].id;
        data['brand_id'] = appData.brand_id[appData.b_index].id;
        data['agency_id'] = appData.agency[appData.agency_id].id;
        data['supplier_no'] = appData.supplier[appData.supp_id].id;
        data['back_supplier_no'] = appData.supplier[appData.b_supp_id].id;
        
        common.bestCurl('POST','/cars/edit',res=>{
            if(res.statusCode == 200){
                if(res.data.code == 1){
                    var flag = 0;
                    var files = this.data.files;
                    var filesNum = this.data.filesNum;
                    console.log(filesNum)
                    if(filesNum>0){
                        wx.showLoading({
                            title: '图片上传中',
                            icon: 'loading',
                            mask:true
                        });
                        for(var index in files){
                            for(var key in files[index]){
                                var kind = files[index][key].kind;
                                if(kind == 2){
                                    var path = files[index][key].url;
                                    let SESSID = wx.getStorageSync('PHPSESSID');
                                    if(SESSID){
                                        var PHPSESSID = '?PHPSESSID='+SESSID;
                                    }else{
                                        PHPSESSID = '?';
                                    }
                                    url=baseUrl+'/cars/add_file'+PHPSESSID;
                                    wx.uploadFile({
                                        url: url,
                                        filePath: path,
                                        name: 'uploadfile',
                                        formData:{
                                            "id": id,
                                            "type":index
                                        },
                                        success: function(res){                        
                                            flag++;
                                            if(filesNum == flag){
                                                wx.hideLoading();
                                                wx.showToast({
                                                    title: '更新成功',
                                                    icon: '',
                                                    duration: 5000
                                                });
                                                setTimeout(res=>{
                                                    wx.redirectTo({
                                                        url: '../list/list'
                                                    });
                                                },2000);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }else{
                        wx.showToast({
                            title: '更新成功',
                            icon: '',
                            duration: 5000
                        });
                        setTimeout(res=>{
                            wx.redirectTo({
                                url: '../list/list'
                            });
                        },2000);
                    }
                }else if(res.data.code == 2){
                    wx.showModal({
                        content: res.data.msg,
                        showCancel: false,
                    });
                }
            }
        },Object.assign({'car_id':id},data,formData))
    }
});

